<template>
  <GridLayout class="root">
    <ScrollView orientation="vertical">
      <StackLayout>
        <GridLayout columns="*, auto" height="380">
          <StackLayout col="0">
            <GridLayout class="tab" columns="*, *">
              <Label :class="'left ' + (isBuy? 'active-left': '')" text="Buy" col="0" @tap="clickLeft()" />
              <Label :class="'right ' + (!isBuy? 'active-right': '' )" text="Sell" col="1" @tap="clickRight()" />
            </GridLayout>
            <GridLayout class="mode" columns="*, *">
              <Label text="Limit" horizontalAlignment="center" col="0" @tap="clickLimit"/>
              <Label text="Market" horizontalAlignment="center" col="1" @tap="clickMarket"/>
            </GridLayout>
            <GridLayout class="indicator" columns="*, *">
              <Image v-if="isLimitPrice" src="~/images/arrow.png" horizontalAlignment="center" col="0"/>
              <Image v-if="!isLimitPrice" src="~/images/arrow.png" horizontalAlignment="center" col="1"/>
            </GridLayout>
            <StackLayout v-if="isLimitPrice" class="price-input" orientation="horizontal">
              <TextField v-model="inputPrice" keyboardType="number"/>
              <Image class="minus" src="~/images/reduce.png" @tap="addInputPrice(-0.000001)"/>
              <Image class="add" src="~/images/add.png"  @tap="addInputPrice(0.000001)"/>
            </StackLayout>
            <Label v-if="!isLimitPrice" class="price" text="The best market price"/>
            <Label v-if="isLimitPrice" class="us-value" :text="calUsRatio"/>
            <StackLayout class="amount-input" orientation="horizontal">
              <TextField :hint="isLimitPrice? 'Amount': (isBuy? 'Total': 'Amount')" v-model="amount" keyboardType="number"/>
              <Label :text="(!isLimitPrice && isBuy)? pairB : pairA"/>
            </StackLayout>
            <Label class="available" :text="available"/>
            <StackLayout v-if="isLimitPrice" class="total-container" orientation="horizontal">
              <Label class="total" text="Total"/>
              <Label class="total-num" :text="totalNum"/>
            </StackLayout>
          <Button :isEnabled="!isTrying" :class="'buy ' + (!isLogin? 'buy-login' : (isBuy? 'buy-btn' : 'sell-btn'))" :text="buttonText" @tap="confirm"/>
          </StackLayout>
          <StackLayout col="1" width="155">
            <GridLayout columns="2*, 3*, 3*" class="trend-label">
              <label col="0" text="Trend"/>
              <label col="1" text="Price"/>
              <label col="2" text="Amount"/>
            </GridLayout>
            <StackLayout class="trend-top">
              <GridLayout v-for="(item, index) in currentSell" columns="2*, 3*, 3*" class="trend-values" :key="index">
                <label col="0" :text="index+1"/>
                <label col="1" :text="item.price.toFixed(5)" class="price-sell"/>
                <label col="2" :text="item.amount.toFixed(5)"/>
              </GridLayout>
            </StackLayout>
            <StackLayout v-if="currentPrice > 0" class="current-price">
              <label class="fir" :text="currentPrice.toFixed(6)"/>
              <label class="sec" :text="usRatio.toFixed(6)"/>
            </StackLayout>
            <StackLayout class="trend-bellow">
              <GridLayout v-for="(item, index) in currentBuy" columns="2*, 3*, 3*" class="trend-values" :key="index">
                <label col="0" :text="index+1"/>
                <label col="1" :text="item.price.toFixed(5)" class="price-buy"/>
                <label col="2" :text="item.amount.toFixed(5)"/>
              </GridLayout>
            </StackLayout>
          </StackLayout>
        </GridLayout>
        <GridLayout columns="*, auto,*, auto, *" class="actions">
          <StackLayout col="0" orientation="horizontal" horizontalAlignment="center" verticalAlignment="center" @tap="onReceivePressed">
            <image  src="~/images/receieve.png" />
            <label text="Receive"/>
          </StackLayout>
          <AbsoluteLayout col="1" class="divider" verticalAlignment="center"/>
          <StackLayout col="2" orientation="horizontal" horizontalAlignment="center" verticalAlignment="center" @tap="onCollectPressed">
            <image  :src="this.isMarked? '~/images/marked.png' : '~/images/mark.png'" />
            <label text="Collect"/>
          </StackLayout>
          <AbsoluteLayout col="3" class="divider" verticalAlignment="center"/>
          <StackLayout col="4" orientation="horizontal"  horizontalAlignment="center" verticalAlignment="center" @tap="onChartPressed">
            <image  src="~/images/chart.png"/>
            <label text="Chart"/>
          </StackLayout>

        </GridLayout>
        <GridLayout columns="*, auto" class="orders">
          <Label col="0" text="Open Orders" verticalAlignment="center"/>
          <label class="orders-btn" col="1" text="All" @tap="toOpenOrders" verticalAlignment="center"/>
        </GridLayout>
        <GridLayout>
          <Image width="73" marginTop="50" height="103" v-if="orders.length == 0" src="~/images/no-record.png"/>
          <StackLayout class="cells" height="auto">
            <order-item v-for="(item, index) in orders" v-bind:key="index" :order="item" :isBuy="isBuy" :onCanceld="orderCanceled" noPairDisplay="true"/>
          </StackLayout>
        </GridLayout>
      </StackLayout>
    </ScrollView>
    <GridLayout v-if="showPaymentPassword" class="mask">
      <StackLayout class="dialog" verticalAlignment="center">
        <label text="Please input your payment password" textWrap/>
        <TextField ref="paymentPassword" v-model="paymentPassword" secure/>
        <DockLayout stretchLastChild="false" class="func">
          <Label text="Haven't set" dock="left" @tap="setPaymentPass"/>
          <Label text="Change password" dock="right" @tap="changePayPass"/>
        </DockLayout>
        <GridLayout columns="*, auto, *" class="dialog-btns">
          <button text="Cancel" col="0" @tap="cancelPayPassInput"/>
          <AbsoluteLayout class="divider" col="1"/>
          <button text="OK" col="2" class="ok-btn" @tap="afterPayPassInput"/>
        </GridLayout>
      </StackLayout>
    </GridLayout>
  </GridLayout>
</template>
<script>
import {dataBus} from '~/business/DataBus'
import OrderItem from '~/components/common/OrderItem'
import Orders from '~/components/Orders'
require( "nativescript-localstorage" )
import Login from '~/components/login/Login'
const platform = require("tns-core-modules/platform")
import Security from '~/components/Security'
import loaderGen, {loadingOption} from '~/utils/loading'
const dialogs = require('tns-core-modules/ui/dialogs')
import Deposit from '~/components/Deposit'
import Chart from '~/components/common/Chart'
import ChangePaymentPass from '~/components/common/ChangePaymentPass'

export default {
  data() {
    return {
      isBuy: false,
      isLimitPrice: true,
      availableB: 0,
      availableA: 0,
      inputPrice:'',
      amount: '',
      isLogin: false,
      isIOS: platform.isIOS,
      currentBuy: [],
      currentSell:[],
      isTrying: false,
      orders: [],
      isMarked: false,
      showPaymentPassword: false,
    }
  },
  components: {
    'order-item': OrderItem,
  },
  props: ['pair', 'isSell'],
  watch: { 
    pair: function(newVal, oldVal) {
      this.setParas()
    }
  },
  computed: {
    pairA() {
      return this.pair.split('/')[0]
    },
    pairB() {
      return this.pair.split('/')[1]
    },
    totalNum() {
      let val = this.amount
      if (this.amount.length == 0) {
        val = '0'
      }
      return (parseFloat(this.inputPrice) * parseFloat(val)).toFixed(6) + this.pairB
    },
    available() {
      return 'Available ' + (this.isBuy? this.availableB : this.availableA) + 
        (this.isBuy? this.pairB : this.pairA)
    },
    calUsRatio() {
      let val = (0.0).toFixed(6)
      if (this.usRatio != 0) {
        val = (parseFloat(this.inputPrice)/this.currentPrice * this.usRatio).toFixed(6)
      }
      return '≈'+val+'$'
    },
    currentPrice() {
      if (dataBus.markets.coinPrices) {
          let priceA = dataBus.markets.coinPrices[this.pairA].usdPrice
          let priceB = dataBus.markets.coinPrices[this.pairB].usdPrice
          return (priceA/priceB)
      } else {
          return 0
      }
    },
    usRatio() {
        if (dataBus.markets.coinPrices) {
            return dataBus.markets.coinPrices[this.pairA].usdPrice
        } else {
            return 0
        }
    },
    buttonText() {
      if (!this.isLogin) {
        return 'Login to Exchange'
      }
      return this.isBuy? 'Buy ' + this.pairA : 'Sell ' + this.pairA
    }
  },
  methods: {
    clickLeft() {
      this.isBuy = true;
      this.orders = []
      this.loadOrders()
    },
    clickRight() {
      this.isBuy = false;
      this.orders = []
      this.loadOrders()
    },
    clickLimit() {
      this.isLimitPrice = true
      this.inputPrice = this.currentPrice.toFixed(6)
      this.amount = '';
    },
    clickMarket() {
      this.isLimitPrice = false
      this.inputPrice = this.currentPrice.toFixed(6)
      this.amount = '';
    },
    addInputPrice(incre) {
      let val = (parseFloat(this.inputPrice) + incre).toFixed(6)
      this.inputPrice = val
    },
    onLoginBack() {
      const self = this
      this.isLogin = true
      dataBus.loadWalletDetail({
        onSuccess: () => {
          self.setParas()
        }
      })
    },
    confirm() {
      if (!this.isLogin) {
        this.$navigateTo(Login)
        dataBus.loginBack = this.onLoginBack.bind(this)
        return
      }
      if (this.amount.length == 0 || isNaN(this.amount)) {
        alert('Please input the Amount')
        return
      }
      if (this.isLimitPrice) {
        if (this.inputPrice.length == 0 || isNaN(this.inputPrice)) {
          alert('Please input the Price')
          return
        }
      }
      const self = this
      this.isTrying = true
      if (!this.loader) {
        this.loader = loaderGen()
      }
      this.showPaymentPassword = true
      setTimeout(() => {
        self.$refs.paymentPassword.nativeView.focus()
      }, 600);
      //this.loader.show(loadingOption)
      // dataBus.isExchangePassExist({
      //   onSuccess: ret => {
      //     self.loader.hide()
      //     if (ret != 'false') {
      //       self.showPaymentPassword = true
      //         setTimeout(() => {
      //           self.$refs.paymentPassword.nativeView.focus()
      //         }, 600);
            
      //       // prompt({
      //       //   title: "Payment password",
      //       //   message: "Provide your payment password",
      //       //   okButtonText: "OK",
      //       //   cancelButtonText: "Cancel",
      //       //   inputType: dialogs.inputType.password
      //       // }).then(result => {
      //       //   if (result.result) {
      //       //     self.checkFundPassword(result.text)
      //       //   } else {
      //       //     self.isTrying = false
      //       //   }
      //       // });
      //     } else {
      //       self.$navigateTo(Security)
      //     }
      //   },
      //   onError: (code, msg) => {
      //     self.isTrying = false
      //     alert(msg)
      //     self.loader.hide()
      //   }
      // })
      

    },
    toOpenOrders() {
      if (!this.isLogin) {
        this.$navigateTo(Login)
        return
      }
      const self = this
      this.$navigateTo(Orders, {
        props: {
          pair: self.pair,
          isBuy: self.isBuy
        }
      })
    },
    onOrdersChange() {
      this.openOrders = dataBus.orders.opened
    },
    checkFundPassword(pass) {
      const self = this
      self.loader.show(loadingOption)
      dataBus.checkFundPassword(pass, {
        onSuccess: (ret) => {
          if (ret != 'false') {
            self.createOrder()
          } else {
            alert('Wrong payment password')
            self.loader.hide()
            self.isTrying = false
          }
        },
        onError: (code, msg) => {
          alert(msg)
          self.loader.hide()
          self.isTrying = false
        }
      })
    },
    createOrder() {
      const self = this
      let para = {
        quoteCoinId: this.pairB,
        baseCoinId: this.pairA,
        amount: parseFloat(this.amount),
        action: this.isBuy ? 0 : 1,
      }
      if (this.isLimitPrice) {
        para.price = parseFloat(this.inputPrice)
      }
      dataBus.createOrder(this.isLimitPrice, para, {
        onError: (code, msg) => {
          self.loader.hide()
          alert(msg)
          self.isTrying = false
        },
        onSuccess: () => {
          self.loader.hide()
          self.amount = ''
          alert({
            title: '',
            message: 'Your order successfully created',
            okButtonText: 'OK'
          })
          self.isTrying = false
          self.loadOrders()
        }
      })
    },
    loadOrders() {
      const self = this
      dataBus.loadOrders(this.pairB, this.pairA, this.isBuy, {
        onSuccess: (ret) => {
          self.orders = ret
        }
      })
    },
    setParas() {
      this.isMarked = dataBus.isMarked(this.pair)
      this.inputPrice = this.currentPrice.toFixed(6)
      if (this.isLogin && dataBus.wallet.balances && this.pairB in dataBus.wallet.balances) {
        this.availableB = dataBus.wallet.balances[this.pairB].available
        this.availableA = dataBus.wallet.balances[this.pairA].available
      }
      this.loadOrders()
      this.loadLatestExchange()
    },
    orderCanceled() {
      this.loadOrders()
    },
    loadLatestExchange() {
      const that = this
      dataBus.loadLatestExchange(this.pairA, this.pairB, {
        onSuccess: ret => {
          let sell = ret.sellOrders
          let buy = ret.buyOrders
          that.currentSell = sell
          that.currentBuy = buy
        }
      })
    },
    onReceivePressed() {
      const self = this
      action("Please choose a coin", "Cancel", [this.pairA, this.pairB])
        .then(result => {
          if (result != 'Cancel') {
            self.$navigateTo(Deposit, {
              props: {
                symbol: result
              }
            })
          }
        });
    },
    onCollectPressed() {
      dataBus.markPair(this.pair)
      this.isMarked = dataBus.isMarked(this.pair)
    },
    onChartPressed() {
      const self = this
      this.$navigateTo(Chart, {
        props: {
          pair: self.pair,
        }
      })
    },
    cancelPayPassInput() {
      this.showPaymentPassword = false
      this.isTrying = false
    },
    afterPayPassInput() {
      if (this.paymentPassword.length > 0) {
        this.checkFundPassword(this.paymentPassword)
        this.showPaymentPassword = false
      }
    },
    setPaymentPass() {
      this.$navigateTo(Security)
    },
    changePayPass() {
      this.$navigateTo(ChangePaymentPass, {
        props: {
          title: 'Change Password',
        }
      })
    }
  },
  mounted() {
    this.isBuy = !this.isSell
    this.isLogin = !!localStorage.getItem('token')
    this.setParas()
    const that = this
    this.loadExchangeInterval = setInterval(function() {
      that.loadLatestExchange()
    }, 5000)
  },
  beforeDestroy() {
    clearInterval(this.loadExchangeInterval)
  },
}
</script>

<style scoped>
  .root {
    background: #15273E;
  }
  .tab {
    margin-top: 20;
    width: 190;
    height: 30;
  }
  .left, .right {
    color: #5B88B3;
    font-size: 16;
    width: 100%;
    height: 100%;
    text-align: center;
    border-width: 1;
    border-color: #4D759C;
    padding-top: 2;
  }
  .left {
    border-top-left-radius: 15;
    border-bottom-left-radius: 15;
  }

  .right {
    border-top-right-radius: 15;
    border-bottom-right-radius: 15;
  }

  .active-left {
    background: #00CE7D;
    color: white;
    border-width: 0;
    /* background: linear-gradient(to right, #0B84DE, #23B1D5); */
  }
  .active-right {
    background: #E55541;
    color: white;
    border-width: 0;
    /* background: linear-gradient(to right, #23B1D5,  #0B84DE); */
  }
  .mode {
    width:220;
    height: 30;
    margin-top: 20;
    border-bottom-width: 1;
    border-bottom-color: #6292BE;
  }
  .mode label {
    color: white;
    font-size: 12;
  }
  .indicator {
    width: 220;
    height: 18;
    margin-top: -6;
  }
  .indicator image {
    width: 18;
    height: 18;
  }
  .price-input, .amount-input {
    width: 200;
    height: 40;
    border-width: 1;
    border-color: #274867;
  }

  .price-input textfield {
    width: 125;
    height: 100%;
    color: white;
    font-size: 14;
    border-right-width: 1;
    border-right-color: #274867;
    padding-left: 5;
  }
  .minus, .add {
    width: 22;
    height: 22;
  }
  .minus {
    margin-left: 8;
  }
  .add {
    margin-left: 16;
  }
  .us-value {
    width: 200;
    color: #6292BE;
    font-size: 12;
  }
  .amount-input {
    margin-top: 10;
  }
  .amount-input textfield {
    width: 136;
    height: 100%;
    padding-left: 5;
    color: white;
    font-size: 14;
    placeholder-color:rgba(255,255,255,0.5);
  }
  .amount-input label {
    width: 54;
    height: 20;
    color: #6292BE;
    font-size: 14;
    text-align: right;
  }
  .available {
    margin-top: 4;
    width: 200;
    color: #6292BE;
    font-size: 12;
  }
  .total-container {
    margin-top: 22;
    width: 200;
  }
  .total {
    color: #6292BE;
    font-size: 14;
  }
  .total-num {
    margin-left: 3;
    color: white;
    font-size: 14;
  }
  .buy {
    width: 200;
    height: 30;
    font-size: 14;
    color: white;
    margin-top: 22;
    padding: 0;
    text-transform: none;
    border-radius: 4;
  }

  .buy-login {
    background: linear-gradient(to right, #23B1D5, #0B84DE);
  }
  .buy-btn {
    background: #00CE7D;
  }
  .sell-btn {
    background: #E55541;
  }

  .buy:disabled {
    background: #5480A8;
  }
  .buy-android {
    height: 50;
  }
  .price {
    width: 200;
    height: 40;
    color: #6292BE;
    font-size: 14;
  }
  .orders {
    width: 100%;
    height: 50;
    background: linear-gradient(to right, #0B84DE, #23B1D5);
    margin-top: 20;
  }
  .orders>label {
    font-size: 16;
    color: white;
    margin-left: 12;
  }
  .orders-btn {
    font-size: 14;
    color: white;
    width: 50;
    background-color: rgba(0,0,0,0)
  }
  .trend-label {
    height: 17;
    color: #6292BE;
    font-size: 12;
    margin-top: 18;
    margin-bottom: 2;
  }
  .trend-values {
    height: 20;
    margin-top: 10;
    color: #6292BE;
    font-size: 12;
  }
  .trend-top, .trend-bellow {
    height: 150;
  }
  .current-price {
    margin-top: 5;
  }
  .current-price>.fir {
    color: #E55541;
    font-size: 14;
  }
  .current-price>.sec {
    color: #6292BE;
    font-size: 10;
  }
  .price-sell {
    color: #E55541;
  }
  .price-buy {
    color: #00CE7D;
  }
  .actions {
    height: 55;
    border-top-color: #6292BE;
    border-top-width: 0.5;
    border-bottom-color: #6292BE;
    border-bottom-width: 0.5;
  }
  .actions image {
    width: 16;
    height: 16;
  }
  .actions label {
    color: #6292BE;
    font-size: 14;
    margin-left: 2;
  }
  .divider {
    width: 0.5;
    height: 20;
    background-color: #6292BE;
  }
  .mask {
    background-color: rgba(0,0,0,0.5);
    width: 100%;
    height: 100%;
  }

  .dialog {
    width: 300;
    background-color: #22334d;
    border-radius: 4;
  }

  .dialog>label {
    color: white;
    font-size: 16;
    text-align: center;
    margin-top: 34;
    width: 270;
  }

  .dialog textfield {
    width: 100;
    height: 40;
    color: white;
  }
  .func {
    padding-left: 12;
    padding-right: 12;
    margin-top: 10;
  }
  .func>label {
    color: #6292BE;
    font-size: 12;
    border-bottom-width: 1;
    border-bottom-color: #6292BE;
  }
  .dialog-btns {
    color: white;
    font-size: 16;
    height: 43;
    border-top-width: 0.5;
    border-top-color: #264664;
    margin-top: 10;
  }
  .dialog-btns >button {
    background-color: transparent;
    border-width: 1;
    border-color: transparent;
  }

  .ok-btn {
    color: #01ECF4;
    text-transform: none;
  }

</style>
